package com.duan.boot.interceptor;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.duan.boot.common.R;
import com.duan.boot.entity.HomePage;
import com.duan.boot.entity.User;
import com.duan.boot.service.HomePageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.ws.handler.Handler;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;

/**
 * @author duan
 * @date 2022/11/26 18:24
 */
public class UserLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private HomePageService homePageService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = TokenUtil.getRequestToken(request);
        if (StringUtils.isBlank(token)){
            setReturn(response,400, "用户未登录，请先登录");
            return false;
        }

        HomePage homePageUser = homePageService.findByToken(token);
        if (homePageUser==null){
            setReturn(response,400,"用户不存在");
            return false;
        }

        LocalDateTime expireTime =homePageUser.getUserExpireTime()
                .toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime();
        if (expireTime.isBefore(LocalDateTime.now())){
            setReturn(response, 400,"登录凭证失效，请重新登录");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }

    private static void setReturn(HttpServletResponse response, int status, String msg) throws IOException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtil.getOrigin());
        httpResponse.setCharacterEncoding("UTF-8");
        httpResponse.setStatus(400);
        response.setContentType("application/json;charset=utf-8");
        R build = R.build(status, msg);
        String json = JSON.toJSONString(build);
        httpResponse.getWriter().print(json);
    }
}
